package com.jrx.anytxn.reporting.job.unionFile.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.customer.entity.CmCustomerLimitInfo;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.service.limit.ICreditLimitMappingService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.AnyTxnBatchProperties;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.job.unionFile.step.CreditInfoFileProcessor;
import com.jrx.anytxn.reporting.job.unionFile.step.CreditInfoFileReader;
import com.jrx.anytxn.reporting.job.unionFile.step.CreditInfoFileWriter;
import com.jrx.anytxn.reporting.job.unionFile.step.UnionCreditInfoFileListener;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;
import java.util.List;

/**
 * 生成授信信息文件(增量抽取)
 * lbz
 */
@Configuration
@EnableConfigurationProperties(AnyTxnBatchProperties.class)
@EnableBatchProcessing
public class GenerateCreditInfoFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(GenerateCreditInfoFileConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnyTxnBatchProperties anyTxnBatchProperties;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private UnionCreditInfoFileListener unionCreditInfoFileListener;
    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;
    @Autowired
    private ICreditLimitMappingService creditLimitMappingService;
    @Autowired
    private CreditInfoFileProcessor creditInfoFileProcessor;
    @Autowired
    private CreditInfoFileWriter creditInfoFileWriter;


    @Bean
    public Job generateCreditInfoFileJob() {
        return jobBuilderFactory.get("generateCreditInfoFileJob").incrementer(new RunIdIncrementer()).listener(unionCreditInfoFileListener)
                .start(generateCreditInfoFileStep())
                .build();
    }

    @Bean
    public Step generateCreditInfoFileStep(){
        return stepBuilderFactory.get("generateCreditInfoFileStep")
                .<CmCustomerLimitInfo, String>chunk(anyTxnBatchProperties.getFileConfig().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(creditInfoFileReader())
                .processor(creditInfoFileProcessor)
                .writer(creditInfoFileWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anyTxnBatchProperties.getFileConfig().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public MyBatisPagingItemReader<CmCustomerLimitInfo> creditInfoFileReader() {
        logger.info("联盟授信文件批量启动,机构号：{}", ReportingConstant.DEFAULT_ORG_NUMBER);
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);

        BtBatchStatus statuses = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2,
                ReportingConstant.CUTOVER_END,org.getTenantId(),org.getToday());
        String updateTime = null;
        if(null != statuses){
            updateTime = DateUtils.format(statuses.getCreateTime(),"yyyy-MM-dd HH:mm:ss");
        }

        //获取需要获取的节点信息
        List<String> limitIdList = creditLimitMappingService.selectByTenantId(org.getTenantId());

        return new CreditInfoFileReader(sqlSessionFactory,anyTxnBatchProperties.getFileConfig().getPageSize(),updateTime,limitIdList);
    }

}
